package cn.tedu._03vehicle.base.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_REQUEST_COUNT = 3;
    private static final int MAX_REQUEST_WINDOW_SIZE = 60;
    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();
    private final ConcurrentHashMap<String, LocalDateTime> listResetTimes = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("访问频率拦截器preHandle方法执行");
        HttpSession session = request.getSession();
        String clientIp = request.getRemoteAddr();
        LocalDateTime listTime = listResetTimes.get(clientIp);
        if(listTime == null || LocalDateTime.now().isAfter(listTime.plusSeconds(MAX_REQUEST_WINDOW_SIZE))){
            clientCounts.put(clientIp, 0);
            listResetTimes.put(clientIp, LocalDateTime.now());
        }
        Integer i = clientCounts.get(clientIp);
        i+=1;
        clientCounts.put(clientIp, i);
        log.warn("客户端{}的请求次数为{}", clientIp, i);
        if(i > MAX_REQUEST_COUNT){
            log.debug("访问频率拦截器preHandle方法返回false");
            log.warn("访问频率拦截器拦截了客户端{}的请求", clientIp);
            throw new RuntimeException("访问频率过高");
        }
        log.debug("访问频率拦截器preHandle方法返回true");
        return true;
    }
}
